using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster.Business
{
	public partial class FormController
	{
		
#region Database Related Methods
		
		private void GetFormInfo()
		{
			
			_formInfo = CBO.FillObject<FormInfo>(Code5Systems.FormMaster.Data.DataProvider.Instance().GetForm(_moduleId));
			if (_formInfo != null)
			{
				_formSettings = Utility.GetFormSettings(this._moduleId);
				_formInfo.ConnectionString = Utility.DecryptString(_formInfo.ConnectionString);
				_formInfo.ExtTableConnStr = Utility.DecryptString(_formInfo.ExtTableConnStr);
				FormPageController pageCtlr = new FormPageController();
				_pages = pageCtlr.ListFormPagesByFormID(_formInfo.FormID);
				if (Pages.Count == 0)
				{
					FormPageInfo objPageInfo = new FormPageInfo();
					objPageInfo.FormID = _formInfo.FormID;
					objPageInfo.PageNum = 1;
					objPageInfo.TableColumns = _formInfo.TableColumns;
					objPageInfo.TableRows = _formInfo.TableRows;
					objPageInfo.LabelPosition = _formInfo.LabelPosition;
					objPageInfo.ShortName = string.Format(Localization.GetString("FormPage", Utility.GetSharedResourceFile()), 1);
					
					if (string.IsNullOrEmpty(_formInfo.FormDefinition))
					{
						objPageInfo.PageData = Constants.DEFAULT_PAGE;
					}
					else
					{
						objPageInfo.PageData = Utility.FixLegacyLabels(_formInfo.FormDefinition);
					}
					
					objPageInfo.ExtIdentityColumn = _formInfo.ExtIdentityColumn;
					objPageInfo.ExtTableConnStr = _formInfo.ExtTableConnStr;
					objPageInfo.ExtTableName = _formInfo.ExtTableName;
					
					if (HttpContext.Current.User.Identity.IsAuthenticated)
					{
						objPageInfo.CreatedByID = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().UserID;
						objPageInfo.LastModifiedByID = objPageInfo.CreatedByID;
					}
					else
					{
						objPageInfo.CreatedByID = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().AdministratorId;
						objPageInfo.LastModifiedByID = objPageInfo.CreatedByID;
					}
					
					objPageInfo.CreatedDate = DateTime.Now;
					objPageInfo.LastModifiedDate = DateTime.Now;
					objPageInfo.FormPageID = pageCtlr.AddFormPage(objPageInfo);
					_formInfo.CurrentPage = objPageInfo;
					Pages.Add(objPageInfo);
				}
				
				if (_formInfo.CurrentPage == null)
				{
					_formInfo.CurrentPage = Pages.Find(p => p.PageNum == 1);
				}
			}
		}
		
		
		public List<FormInfo> List()
		{
			
			return CBO.FillCollection<FormInfo>(Code5Systems.FormMaster.Data.DataProvider.Instance().ListForm());
			
		}
		
		public int Add(FormInfo objForm)
		{
			int formId = -1;
			formId = System.Convert.ToInt32(Code5Systems.FormMaster.Data.DataProvider.Instance().AddForm(objForm.PortalID, objForm.ModuleID, objForm.FormName, objForm.EmailFromAction, objForm.EmailSendFromControl, objForm.FromAddress, objForm.BccAddress, objForm.EmailSendAction, objForm.EmailSendTo, objForm.EmailSendToControl, objForm.SaveData, objForm.TableColumns, objForm.TableRows, objForm.TableClass, objForm.LabelPosition, objForm.ShowCcMe, objForm.EmailCcMeControl, Utility.EncryptString(objForm.ConnectionString), objForm.FormQuery, objForm.UseCaptcha, objForm.CaptchaCharacters, objForm.UseExtTable, objForm.ExtIdentityColumn, Utility.EncryptString(objForm.ExtTableConnStr), objForm.ExtTableName, objForm.ReplyToAction, objForm.ReplyTo, objForm.ReplyToControl, objForm.FormDefinition, objForm.CreatedByID, objForm.ExtTableForEachPage));
			//_formInfo = objForm
			//_formInfo.FormID = formId
			this.GetFormInfo();
			return formId;
		}
		
		public void Update(FormInfo objForm)
		{
			
			_formInfo = objForm;
			Code5Systems.FormMaster.Data.DataProvider.Instance().UpdateForm(objForm.ModuleID, objForm.FormName, objForm.EmailFromAction, objForm.FromAddress, objForm.EmailSendFromControl, objForm.BccAddress, objForm.EmailSendAction, objForm.EmailSendTo, objForm.EmailSendToControl, objForm.SaveData, objForm.TableColumns, objForm.TableRows, objForm.TableClass, objForm.LabelPosition, objForm.ShowCcMe, objForm.EmailCcMeControl, Utility.EncryptString(objForm.ConnectionString), objForm.FormQuery, objForm.UseCaptcha, objForm.CaptchaCharacters, objForm.UseExtTable, objForm.ExtIdentityColumn, Utility.EncryptString(objForm.ExtTableConnStr), objForm.ExtTableName, objForm.ReplyToAction, objForm.ReplyTo, objForm.ReplyToControl, objForm.FormDefinition, objForm.LastModifiedByID, objForm.ExtTableForEachPage);
			
		}
		
		public void Delete(int formID)
		{
			
			Code5Systems.FormMaster.Data.DataProvider.Instance().DeleteForm(formID);
			
		}
		
		public void UpdateFormDefinition(int moduleId, string formDefinition, int lastModifiedById)
		{
			Code5Systems.FormMaster.Data.DataProvider.Instance().UpdateFormDefinition(moduleId, formDefinition, lastModifiedById);
			_formInfo.FormDefinition = formDefinition;
		}
		
		public bool HasUserPosted(int moduleId, int userId)
		{
			
			return Code5Systems.FormMaster.Data.DataProvider.Instance().HasUserPosted(moduleId, userId);
			
		}
		
		public DataTable GetQueryData(string connString, string strQuery)
		{
			DataTable dt = null;
			
			if (!(strQuery.StartsWith("Select", StringComparison.OrdinalIgnoreCase) || strQuery.StartsWith("Exec", StringComparison.OrdinalIgnoreCase) || strQuery.StartsWith("<LDAP", StringComparison.OrdinalIgnoreCase)))
			{
				throw (new InvalidOperationException(Localization.GetString("InvalidQuery", Utility.GetSharedResourceFile())));
			}
			
			if (HttpContext.Current.Request.IsAuthenticated)
			{
				ProfilePropertyDefinitionCollection properties = this.GetProfileProperties();
				
				HttpCookie oCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
				FormsAuthenticationTicket userTicket = FormsAuthentication.Decrypt(oCookie.Value);
				UserInfo objUser = UserController.GetUserByName(this._formInfo.PortalID, userTicket.Name);
				
				if (objUser != null)
				{
					strQuery = strQuery.Replace("#UserID#", objUser.UserID.ToString());
					strQuery = strQuery.Replace("#UserName#", objUser.Username);
					strQuery = strQuery.Replace("#FullName#", string.Format("{0} {1}", objUser.FirstName, objUser.LastName));
					strQuery = strQuery.Replace("#DisplayName#", objUser.DisplayName);
					foreach (ProfilePropertyDefinition profProperty in properties)
					{
						strQuery = strQuery.Replace("#" + profProperty.PropertyName + "#", objUser.Profile.GetPropertyValue(profProperty.PropertyName));
					}
				}
			}
			
			try
			{
				//Try to replace URL Tokens with Querystring Parameters
				Regex reUrl = new Regex("#URL:\\w+#");
				string param = default(string);
				string cleanParam = default(string);
				foreach (Match oMatch in reUrl.Matches(strQuery))
				{
					param = oMatch.Value;
					param = param.Replace("#URL:", "");
					param = param.Replace("#", "");
					if (HttpContext.Current.Request.QueryString[param] != null)
					{
						cleanParam = Utility.CleanInputAll(HttpContext.Current.Request.QueryString[param]);
						strQuery = strQuery.Replace(oMatch.Value, cleanParam);
					}
					else
					{
						throw (new Exception(string.Format(Localization.GetString("MissingUrlParam", Utility.GetSharedResourceFile()), param)));
					}
				}
				
				//Try to replace Session Tokens with Sesson Values
				Regex reSession = new Regex("(?i:#SESSION:)\\w+#");
				foreach (Match oMatch in reSession.Matches(strQuery))
				{
					param = oMatch.Value;
					param = param.Replace("#SESSION:", "");
					param = param.Replace("#", "");
					if (HttpContext.Current.Session[param] != null)
					{
						cleanParam = Utility.CleanInputAll((HttpContext.Current.Session[param]).ToString());
						strQuery = strQuery.Replace(oMatch.Value, cleanParam);
					}
					else
					{
						throw (new Exception(string.Format(Localization.GetString("MissingSessionParam", Utility.GetSharedResourceFile()), param)));
					}
				}
				
				//Try to replace Cascading Category Tokens with the Form Post Values
				Regex reCategory = new Regex("(?i:#CASCADE:)\\w+#");
				foreach (Match oMatch in reCategory.Matches(strQuery))
				{
					param = oMatch.Value;
					param = param.Replace("#CASCADE:DO_NOT_EDIT#", "category");
					if (HttpContext.Current.Request.Form[param] != null)
					{
						cleanParam = Utility.CleanInputAll(HttpContext.Current.Request.Form[param]);
						strQuery = strQuery.Replace(oMatch.Value, cleanParam);
					}
					else
					{
						dt = new DataTable();
						return dt;
					}
				}
				
				dt = Code5Systems.FormMaster.Data.DataProvider.Instance().ExecuteSQL(connString, strQuery);
				
			}
			catch (Exception ex)
			{
				dt = new DataTable();
				dt.Columns.Add("Results");
				DataRow dr = dt.NewRow();
				dr["Results"] = ex.Message;
				dt.Rows.Add(dr);
			}
			
			if (dt.Rows.Count == 0)
			{
				dt.Columns.Clear();
				dt.Columns.Add("Results");
				DataRow dr = dt.NewRow();
				dr["Results"] = Localization.GetString("InvalidQuery", Utility.GetSharedResourceFile());
				dt.Rows.Add(dr);
			}
			
			return dt;
			
		}
		
		public DataSet ExecuteDataSet(string connectionString, string query)
		{
			return Code5Systems.FormMaster.Data.DataProvider.Instance().ExecuteDataSet(connectionString, query);
		}
		
		public void VerifyPageNumbers()
		{
			FormPageController pageCtlr = new FormPageController();
			Pages.Sort((p1, p2) => p1.PageNum.CompareTo(p2.PageNum));
			for (int i = 0; i <= Pages.Count - 1; i++)
			{
				if (Pages[i].PageNum != i + 1)
				{
					if (Pages[i].ShortName == string.Format(Localization.GetString("FormPage", Utility.GetSharedResourceFile()), Pages[i].PageNum))
					{
						Pages[i].ShortName = string.Format(Localization.GetString("FormPage", Utility.GetSharedResourceFile()), i + 1);
					}
					Pages[i].PageNum = i + 1;
					pageCtlr.UpdateFormPage(Pages[i]);
				}
			}
		}
		
		
#endregion
		
	}
}


